<!-- 兑换券 -->
<template>
  <div class="content">
    <div class="cloud-header">
      <h2>{{title}}</h2>
    </div>
    <div class="cloud-body">
      <div class="cloud-body-steps">
        <ul class="cloud-desktop-steps">
          <li class="cloud-desktop-step current">1 填写优惠券信息 </li>
          <li class="cloud-desktop-step">2 功能设置 </li>
        </ul>
      </div>
      <div class="cloud-coupon-body">
        <div class="cloud-coupon-left" :style="`background-color: ${card.color || '#f6f6f8'}`">
          <div class="cloud-card">
            <div class="card-header">
              <div class="card-header-panel">
                <div class="logo-area">
                  <span class="logo">
                    <img v-if="card.logo_url" :src="card.logo_url[0]">
                  </span>
                  <p>{{card.brand_name}}</p>
                </div>
                <div class="msg-area">
                  <p class="card-name">
                    {{card.title}}
                  </p>
                  <span class="card-btn">
                    使用
                  </span>
                </div>
              </div>
              <div class="card-usage">
                <ul>
                  <!--<li>
                    <span class="usage-label">使用条件:</span>
                    <span class="usage-time-preview">适用于水果;</span>
                    <span class="usage-limit-preview">不适用于海产哦</span>
                  </li> -->
                  <li>
                    <span class="usage-label">可用时间:</span>
                    <span class="usage-time-preview">2020.06.23-2020.06.23</span>
                    <span class="usage-limit-preview">，周一至周日</span>
                  </li>
                </ul>
              </div>
            </div>
            <div class="card-cover">
              <ul class="card-cover-list">
                <div class="li_panel">
                  <div class="section_card_intro" v-if="card.icon_url_list">
                    <div class="cover_wrap" id="js_cover_preview"><img :src="card.icon_url_list[0]"></div>
                    <div class="cover_summary">
                      <span id="js_abstract_preview">{{card.abstract}}</span>
                    </div>
                  </div>
                </div>
              </ul>
            </div>
            <div class="card-last-cell">
              <ul class="list">
                <li>
                  <div class="list-item">
                    <div class="li_content">
                      <p>适用门店</p>
                    </div>
                    <span class="icon h-icon-right"></span>
                  </div>
                </li>
                <li>
                  <div class="list-item list-item-b">
                    <div class="li_content">
                      <p>公众号</p>
                    </div>
                    <span class="icon h-icon-right"></span>
                  </div>
                </li>
              </ul>
            </div>
            <div class="card-last-cell card-last-detail">
              <ul class="list">
                <li>
                  <div class="list-item list-item-b">
                    <div class="li_content">
                      <p>自行第一入口(选填)</p>
                    </div>
                    <span class="icon h-icon-right"></span>
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <div class="cloud-coupon-right">
          <h3 class="title">基本信息</h3>
          <Form :label-width="110" mode="single" :model="card" ref="form" showErrorTip :rules="validRules">
            <FormItem label="门店LOGO" prop="logo_url">
              <Upload v-model="card.logo_url" mode="wechat"></Upload>
            </FormItem>
            <FormItem label="门店名称" prop="brand_name">
              <input type="text" v-width="392" v-model="card.brand_name" />
              <p class="frm_tips">门店名不得含有区域地址信息（如，北京市XXX公司）</p>
            </FormItem>
            <FormItem label="卡券类型" prop="type">
              <Select v-model="card.type" v-width="211" :datas="cardTypeList"></Select>
            </FormItem>
            <FormItem label="卡券标题" prop="title">
              <input type="text" v-width="392" v-model="card.title" />
              <p class="frm_tips">门店名不得含有区域地址信息（如，北京市XXX公司）</p>
            </FormItem>
            <FormItem label="卡券颜色" prop="color">
              <ColorPicker v-model="card.color" :colors="colors"></ColorPicker>
            </FormItem>
            <FormItem label="兑换内容" prop="gift" v-if="card.type=='GIFT'">
              <input type="text" v-width="211" v-model="card.gift" />
              <p class="frm_tips">兑换券专用，填写兑换内容的名称</p>
            </FormItem>
            <FormItem label="折扣额度" prop="discount" v-if="card.type=='DISCOUNT'">
              <input type="text" v-width="211" v-model="card.discount" /><span class="input_sub_msg">折</span>
              <p class="frm_tips">请填写1-9.9之间的数字，精确到小数点后1位</p>
            </FormItem>
            <FormItem label="减免金额" prop="reduce_cost" v-if="card.type=='CASH'">
              <input type="text" v-width="211" v-model="card.reduce_cost" /><span class="input_sub_msg">元</span>
              <p class="frm_tips">减免金额只能是大于0.01的数字</p>
            </FormItem>
            <FormItem label="最低消费" prop="least_cost" v-if="card.type=='CASH'">
              <span>满&nbsp;&nbsp;</span><input type="text" v-width="211" v-model="card.least_cost" /><span class="input_sub_msg">可用</span>
            </FormItem>
            <FormItem label="有效期" prop="timeType">
              <div class="cloud-coupon-form-item">
                <Radio v-width="80" :value="1" v-model="card.timeType">固定日期</Radio>
                <DateRangePicker v-width="230" v-model="card.time_quantum" format="YYYY-MM-DD" :disabled="card.timeType !== 1"></DateRangePicker>
              </div>
              <div class="cloud-coupon-form-item">
                <Radio v-width="80" :value="2" v-model="card.timeType">领取后，</Radio>
                <span>
                  <Select prop="fixed_begin_term" :disabled="card.timeType !== 2" v-width="100" v-model="card.fixed_begin_term" :datas="dayStart"></Select>生效，有效期 <Select :disabled="card.timeType !== 2" v-width="100" v-model="card.fixed_term" :datas="dayEnd"></Select>
                </span>
              </div>
            </FormItem>
            <FormItem label="可用时段">
              <div class="cloud-coupon-form-item">
                <Radio :value="1" v-model="card.timeLimit">全部时段</Radio>
              </div>
              <div class="cloud-coupon-form-item">
                <Radio :value="2" v-model="card.timeLimit">部分时段</Radio>
                <p style="padding-left: 20px" v-if="card.timeLimit == 2">
                  日期： <Checkbox v-model="card.time_type" :datas="weekList"></Checkbox>
                </p>
                {{card.begin_time}}{{card.end_time}}
                <p style="padding-left: 20px" v-if="card.timeLimit == 2">
                  时间： <DatePicker v-width="120" v-model="card.begin_time" type="time"></DatePicker>&nbsp;至&nbsp;<DatePicker v-width="120" v-model="card.end_time" type="time"></DatePicker>
                </p>
              </div>
            </FormItem>
            <h3 class="title">优惠详情</h3>
            <FormItem label="领券限制" prop="get_limit">
              <input type="text" v-width="211" v-model="card.get_limit" /><span class="input_sub_msg">张</span>
              <p class="frm_tips">每个用户领券上限，如不填，则默认为1</p>
            </FormItem>
            <!--<FormItem label="使用条件">
              <div class="cloud-coupon-form-item">
                <span style="padding-right: 15px">优惠共享</span>
                <Select v-width="100" v-model="card.demo" :datas="param"></Select>
              </div>
            </FormItem> -->
            <FormItem label="封面图片" prop="icon_url_list">
              <Upload v-model="card.icon_url_list" mode="wechat"></Upload>
            </FormItem>
            <FormItem label="封面简介" prop="abstract">
              <input type="text" v-width="211" v-model="card.abstract" />
            </FormItem>
            <FormItem label="使用须知" prop="description">
              <textarea type="text" v-model="card.description"></textarea>
              <p class="frm_tips">请填写优惠券的的注意事项</p>
            </FormItem>
            <h3 class="title">使用设置</h3>
            <FormItem label="库存" prop="quantity">
              <input type="text" v-width="211" v-model="card.quantity" /><span class="input_sub_msg">份</span>
              <p class="frm_tips">设置优惠券库存数量，如不填，则默认为2</p>
            </FormItem>
            <FormItem label="用户设置">
              <h-switch v-model="card.can_share">用户可以分享领券链接</h-switch>
              &nbsp;&nbsp;&nbsp;&nbsp;
              <h-switch v-model="card.can_give_friend">用户领券后可转赠其他好友</h-switch>
            </FormItem>
            <FormItem label="等级限制">
              <Radio v-model="card.card_level" :datas="param_level"></Radio>
            </FormItem>
            <h3 class="title">门店信息</h3>
            <!-- <FormItem label="适用门店">
              <Radio :value="true" v-model="card.use_all_locations" disabled>全部门店适用</Radio>
              &nbsp;&nbsp;&nbsp;&nbsp;
              <Radio :value="false" v-model="card.use_all_locations">选择门店</Radio>
            </FormItem> -->
            <FormItem label="选择门店">
              <Select v-model="card.location_id_list" :datas="shopList" :multiple="true" keyName="poi_id" titleName="branch_name"></Select>
            </FormItem>
            <FormItem label="操作提示" prop="center_sub_title">
              <input type="text" v-width="211" v-model="card.center_sub_title" /><span class="input_sub_msg"></span>
              <p class="frm_tips">建议引导用户到店出示卡券，由店员完成核销操作</p>
            </FormItem>
            <FormItem>
              <!-- <Button color="primary" :loading="isLoading" @click="compile" v-if="isUpdate && card.card_id">更新卡券</Button> -->
              <Button color="primary" :loading="isLoading" @click="compile" v-if="isUpdate && !card.card_id">审核提交</Button>
              <Button color="primary" :loading="isLoading" @click="submit" v-if="!isUpdate">提交卡券</Button>
            </FormItem>
          </Form>
        </div>
        <div class="clear"></div>
      </div>
    </div>
  </div>
</template>
<script type="text/javascript">
import Vue from 'vue';
import ColorPicker from 'heyui/lib/components/color-picker';
import Upload from '@/components/upload.vue';
import { setCard } from '@/utils';
Vue.component('ColorPicker', ColorPicker);
export default {
  components: {
    Upload
  },
  data() {
    return {
      _uniqueid: '',
      title: '添加优惠券',
      isLoading: false,
      isUpdate: false,
      shopList: [],
      card: {
        'timeType': 1,
        'type': 'GIFT',
        'timeLimit': 1,
        'brand_name': '',
        'title': '',
        'discount': '',
        'time_quantum': {
          'start': '',
          'end': ''
        },
        'get_limit': '',
        'logo_url': [],
        'icon_url_list': [],
        'time_type':[],
        'location_id_list': [],
        'abstract': '优惠券使用规则',
        'description': '',
        'quantity': '',
        'card_level': 1,
        'center_sub_title': '请出示右上角二维码',
        'use_all_locations': false
      },
      step: 0,
      cardTypeList: [
        { key: 'GIFT', title: '兑换券' }
      ],
      param_level: [
        { key: '1', title: '初级' },
        { key: '2', title: '中级' },
        { key: '3', title: '高级' }
      ],
      weekList: [
        { title: '星期一', key: 'MONDAY' },
        { title: '星期二', key: 'TUESDAY' },
        { title: '星期三', key: 'WEDNESDAY' },
        { title: '星期四', key: 'THURSDAY' },
        { title: '星期五', key: 'FRIDAY' },
        { title: '星期六', key: 'SATURDAY' },
        { title: '星期日', key: 'SUNDAY' }
      ],
      colors: ['#63b359', '#2c9f67', '#509fc9', '#5885cf', '#9062c0', '#d09a45', '#e4b138', '#ee903c', '#f08500', '#a9d92d', '#dd6549', '#cc463d', '#cf3e36', '#5E6671'],
      validRules: {
        rules: {
          brand_name: {
            maxLen: 12
          },
          title: {
            maxLen: 9
          },
          //即notice
          center_sub_title: {
            maxLen: 16
          },
          description: {
            maxLen: 1024
          },
          quantity: {
            type: 'number',
            valid(prop, parent, data) {
              if (prop <= 0) {
                return '必须大于0'
              }
              return true;
            }
          },
          get_limit: {
            type: 'number',
            valid(prop, parent, data) {
              if (prop <= 0) {
                return '必须大于0'
              }
              return true;
            }
          }
        },
        combineRules: [{
          refs: ['type', 'gift'],
          valid(a, b) {

            if (a === 'GIFT' && !b) {
              return '兑换内容不能为空'
            }

            return true;
          }
        }, {
          refs: ['type', 'discount'],
          valid(a, b) {

            if (a === 'DISCOUNT' && (b < 1 || b > 9.9)) {
              return '折扣值不符合规范'
            }

            return true;
          }
        }, {
          refs: ['type', 'reduce_cost', 'least_cost'],
          valid(a, b, c) {
            if (a === 'CASH' && (!b || !c || b < 0.01 || b >= c)) {
              return '抵扣金额不规范'
            }

            return true;
          }
        }],
        required: ['logo_url', 'brand_name', 'title', 'type', 'color', 'center_sub_title', 'description', 'timeType']
      }
    };
  },
  /**
   * 计算属性
   * @type {Object}
   */
  computed: {
    dayStart() {
      let days = [];
      let day = 90;
      for (let i = 0; i <= day; i++) {
        if (i) {
          days.push({ key: i, title: i + '天' });
        } else {
          days.push({ key: i, title: "当天" });
        }
      }
      return days;
    },
    dayEnd() {
      let days = [];
      let day = 90;
      for (let i = 1; i <= day; i++) {
        days.push({ key: i, title: i + '天' });
      }
      return days;
    }
  },
  /**
   * 页面加载执行
   * @return {[type]} [description]
   */
  mounted() {
    this._uniqueid = this.$cloud.userInfo()._uniqueid
    if (this.$route.params.id) {
      this.title = '修改卡券';
      this.isUpdate = true;
      this.getData(this.$route.params.id);
    }
    this.getShopList();
  },
  methods: {
    /**
     * 获取商品列表
     * @return {[type]} [description]
     */
    getShopList() {
      this.$cloud.name('shop').where({ _uniqueid: this._uniqueid }).limit(-1).select().then(res => {
        console.log('店铺列表', res);
        this.shopList = res;
      }).catch(error => {
        console.log('数据库操作报错', error);
        this.$Notice.error(error.data.msg);
      });
    },
    /**
     * 获取数据信息
     * @param  {[type]} id [description]
     * @return {[type]}    [description]
     */
    getData(id) {
      this.$cloud.name('card').where({ _id: id }).first(this.card, true).then(res => {
        this.card = res;
      }).catch(error => {
        console.log('数据库操作报错', error);
        this.$Notice.error(error.data.msg);
      });
    },
    /**
     * 添加门店数据
     */
    delData(id) {
      this.$cloud.name('card').where({ _id: id }).delete().then(res => {
        console.log('删除操作', id);
        this.$Notice.error('创建卡券失败');
      }).catch(error => {
        this.$Notice.error(error.data.msg);
      });
    },
    /**
     * 执行数据更新
     * @return {[type]} [description]
     */
    compile() {
      let validResult = this.$refs.form.valid();
      if (validResult.result) {
        if (this.card.timeType === 1) {
          if (!this.card.time_quantum.start || !this.card.time_quantum.end) {
            this.$Notice.error('有效期内容不完整');
            return false;
          }
        } else {
          if ((this.card.fixed_begin_term !== 0 && !this.card.fixed_begin_term) || !this.card.fixed_term) {
            this.$Notice.error('有效期内容不完整');
            return false;
          }
        }
        if (this.card.timeLimit === 2) {
          if (!this.card.begin_time || !this.card.end_time) {
            this.$Notice.error('可用时段内容不完整');
            return false;
          }
        }
        this.$cloud.name('card').where({ _id: this.card._id }).update(this.card).then(res => {
          if (res) {
            this.addCard(this.card);
            this.$Notice.success('提交成功');
          } else {
            this.$Notice.error('提交失败');
          }
        }).catch(error => {
          console.log('数据库操作报错', error);
          this.$Notice.error(error.data.msg);
        });
      }
    },
    /**
     * 提交数据
     * @return {[type]} [description]
     */
    submit() {
      this.addData();
    },
    /**
     * 创建卡券
     * @param {[type]} data [description]
     */
    addCard(data) {
      let postData = setCard(this.card);
      console.log('postData', postData);
      this.$cloud.wechat().createCard(postData).then(res => {
        if (res) {
          this.updateCard(data._id, res.card_id);
        } else {
          console.log('res', res);
        }
      }).catch(error => {
        console.log('创建门店报错', error);
        this.$Notice.error(error.data.msg);
        this.delData(data._id);
      });
    },
    /**
     * 添加卡券数据
     */
    addData() {
      let validResult = this.$refs.form.valid();
      if (validResult.result) {
        if (this.card.timeType === 1) {
          if (!this.card.time_quantum.start || !this.card.time_quantum.end) {
            this.$Notice.error('有效期内容不完整');
            return false;
          }
        } else {
          if ((this.card.fixed_begin_term !== 0 && !this.card.fixed_begin_term) || !this.card.fixed_term) {
            this.$Notice.error('有效期内容不完整');
            return false;
          }
        }
        if (this.card.timeLimit === 2) {
          if (!this.card.begin_time || !this.card.end_time) {
            this.$Notice.error('可用时段内容不完整');
            return false;
          }
        }
        console.log('this.card', JSON.stringify(this.card));
        this.$cloud.name('card').insert(this.card, true).then(res => {
          console.log('数据库操作', res);
          if (res) {
            this.addCard(res);
          } else {
            this.$Notice.error('添加卡券失败');
          }
        }).catch(error => {
          console.log('数据库操作报错', error);
          this.$Notice.error(error.data.msg);
        });
      }
    },
    /**
     * 更新卡券数据
     * @return {[type]} [description]
     */
    updateCard(id, card_id) {
      this.$cloud.name('card').where({ _id: id }).update({ card_id: card_id }).then(res => {
        console.log('更新数据库操作', res);
        this.isLoading = false;
        this.$refs.form.resetValid();
        setTimeout(() => {
          this.$router.push('/merchant/coupon');
        }, 1000);
      }).catch(error => {
        this.$Notice.error(error.data.msg);
        console.log('数据库操作报错', error);
      });
    }
  }
};

</script>
<style scoped="true">
.cloud-coupon-body {
  margin: 0 15px;
}

.cloud-coupon-body .h-select-no-autosize {
  display: inline-block;
}

.cloud-coupon-body .cloud-coupon-form-item {
  margin-bottom: 20px;
}

.clear {
  clear: both;
}

.cloud-coupon-body .logo {
  display: block;
  width: 38px;
  height: 38px;
  padding-top: 0;
  margin: 0 auto;
  border-radius: 22px;
  -moz-border-radius: 22px;
  -webkit-border-radius: 22px;
  float: none;
  border: 1px solid #e7e7eb;
  background-color: #fff;
}

.cloud-coupon-body .logo img {
  display: block;
  width: 100%;
  height: 100%;
  border-radius: inherit;
  -moz-border-radius: inherit;
  -webkit-border-radius: inherit;
}

.cloud-coupon-left {
  width: 318px;
  margin: 20px 0;
  float: left;
  min-height: 711px;
  overflow: hidden;
  background: #f6f6f8 url(https://res.wx.qq.com/mpres/zh_CN/htmledition/comm_htmledition/images/pic/cardticket/topbar49d02c.png) no-repeat center 5px;
}

.cloud-card {
  margin: 64px 10px 10px;
}

.card-header {
  margin: 0;
  padding: 0;
  border-bottom: 1px dashed #e7e7eb;
  position: relative;
  background-color: #fff;
  border-radius: 5px 5px 0 0;
  -moz-border-radius: 5px 5px 0 0;
  -webkit-border-radius: 5px 5px 0 0;
}

.card-header-panel {
  padding: 21px 12px 12px;
  min-height: 137px;
  margin-bottom: 18px;
  height: auto;
  text-align: center;
}

.card-header-panel .logo-area {
  position: relative;
  margin-bottom: 7px;
  line-height: 42px;
  color: #9a9a9a;
  margin-top: -40px;
}

.card-header-panel .logo-area .logo {
  display: block;
  width: 38px;
  height: 38px;
  padding-top: 0;
  margin: 0 auto;
  border-radius: 22px;
  -moz-border-radius: 22px;
  -webkit-border-radius: 22px;
  float: none;
  border: 1px solid #e7e7eb;
  background-color: #fff;
  font-size: 24px;
}

.card-header-panel .logo-area p {
  padding: 0;
  margin: 0;
}

.msg-area .card-name {
  font-weight: normal;
  font-size: 28px;

  word-break: break-word;
}

.msg-area .card-btn {
  border-width: 0;
  background-color: #f4f5f9;
  display: inline-block;
  width: 100px;
  overflow: visible;
  padding: 0 22px;
  height: 30px;
  line-height: 30px;
  vertical-align: middle;
  text-align: center;
  text-decoration: none;
  border-radius: 3px;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  font-size: 14px;
  border-width: 1px;
  border-style: solid;
  cursor: pointer;
}

.card-usage {
  text-align: left;
  padding: 0 10px 1em;
  background-color: #fff;
}

.card-usage .usage-label {
  float: left;
  margin-left: -5em;
  color: #222;
}

.card-usage li {
  overflow: hidden;
  padding-left: 5em;
  clear: both;
  color: #8d8d8d;
}

.card-last-cell {
  border-radius: 0 0 5px 5px;
  -moz-border-radius: 0 0 5px 5px;
  -webkit-border-radius: 0 0 5px 5px;
  background-color: #fff;
}

.card-last-cell .list {
  margin: 0 10px;
  border-bottom: 1px solid #e7e7eb;
}

.card-last-cell .list-item {
  position: relative;
  display: block;
  padding: 11px 30px 11px 0;
  border-bottom: 1px solid #e7e7eb;

}

.card-last-cell .list-item p {
  margin: 0;
  padding: 0;
}

.card-last-cell .list:last-child {
  border-bottom-width: 0;
}

.card-last-cell .list-item-b {
  border-bottom: 0;
}

.card-last-cell .list-item .icon {
  position: absolute;
  top: 36%;
  right: 5px;
  width: 16px;
  height: 15px;
  color: #ccc;
}

.card-last-detail {
  margin-top: 15px;
}

.card-cover {
  background-color: #fff;
}

.card-cover ul {
  margin: 0 10px;
}

.section_card_intro {
  position: relative;
  width: 100%;
  height: auto;
  color: #9a9a9a;
  overflow: hidden;
  padding: 0;
  word-wrap: break-word;
  -webkit-hyphens: auto;
  -ms-hyphens: auto;
  hyphens: auto;
  min-height: 24px;

}

.section_card_intro .cover_wrap {
  overflow: hidden;
  max-height: 116px;
  height: auto;
  padding-top: 5px;
}

.section_card_intro img {
  width: 100%;
  margin: 0;
  padding: 0;
}

.section_card_intro .cover_summary {
  height: 24px;
  background: #000;
  background: rgba(0, 0, 0, 0.7);
  margin-top: 0;
  position: absolute;
  z-index: 9;
  left: 0;
  width: 100%;
  bottom: 0;
  color: #fff;
  text-indent: 1em;
}

.cloud-body-steps {
  width: 100%;
  margin: 0 auto;
}

.cloud-coupon-right {
  padding: 20px;
  border: 1px solid #e7e7eb;
  background-color: #f4f5f9;
  min-height: 350px;
  width: calc(100% - 360px);
  float: right;
  margin-top: 20px;
  position: relative;

}

.cloud-coupon-right:after {
  position: absolute;
  content: "";
  display: inline-block;
  width: 0;
  height: 0;
  border-width: 12px;
  border-style: dashed;
  border-color: transparent;
  border-left-width: 0;
  border-right-color: #e7e7eb;
  border-right-style: solid;
  top: 120px;
  left: -12px;
}

.cloud-desktop-steps {
  background-color: #fff;
  border-bottom: 1px solid #e4e8eb;
  text-align: center;
  line-height: 1.4;
  box-sizing: border-box;
  counter-reset: step;
  color: #9a9a9a;
  font-size: 14px;
  list-style-type: none;
}

.cloud-desktop-step {

  vertical-align: top;
  padding: 21px 0;
  position: relative;
  display: inline-block;
}

.current {
  color: #07c160
}

.cloud-desktop-step:after {
  content: "";
  display: inline-block;
  vertical-align: middle;
  margin: 8px 10px;
  width: 30px;
  border-bottom: 2px solid #e4e8eb;
}

.cloud-desktop-steps li:last-child:after {
  width: 0;
}

h3.title {
  font-size: 14px;
  height: 34px;
  line-height: 34px;
  border-bottom: 1px solid #e6e9eb;
  font-weight: normal;
  margin-bottom: 20px;
}

.input_sub_msg {
  padding-left: 5px;
  line-height: 30px;
  font-size: 14px;
}

</style>
